function [C, gammaopt] = gridParameterCanonical(X,Y,params,type)
% calculate best parameter using RBF kernel
% function x = gridParameter(X,Y,params)
% params is matrix with form 
% | xmin  xmax  dx |
% | ymim  ymax  dy |

fprintf('finding optimal C and gamma\n');
global Standardize showGraph;
global gamma;
kfold = 5;
% showGraph = false;
rng(1);
N = size(X,1);
% c = cvpartition(N,'KFold',kfold);

partN = ceil(N/(kfold+1));


if(nargin < 4)
    type = 'rbf';
end

if(nargin < 3)
% loose grid
    xmin = -5;xmax = 15; dx = 2;
    ymin = -15; ymax = 3; dy = 2;
else
    xmin = params(1,1);xmax = params(1,2); dx = params(1,3);
    ymin = params(2,1);ymax = params(2,2); dy = params(2,3);
end

nx = (xmax - xmin)/dx +1;
ny = (ymax - ymin)/dy +1;
fres = zeros(nx,ny);

index1 = 1;
for i = xmin: dx: xmax
    index2 = 1;
    for  j = ymin: dy : ymax
        C = 2.^i;
        scale = 2.^j;  
        sumError = 0;
        for k = 1 : kfold
            trainingX = X(1:k*partN,:);
            trainingY = Y(1:k*partN);
            if(k > kfold)
                testX = X(k*partN+1:partN*(k+1),:);
                testY = Y(k*partN+1:partN*(k+1));          
            else
                testX = X(k*partN+1:end,:);
                testY = Y(k*partN+1:end);
            end
            if(strcmp(type,'rbf'))
                modelTemp = fitcsvm(trainingX,trainingY,'KernelFunction','rbf',...
            'BoxConstraint',C,'KernelScale',scale,'Standardize',Standardize);
            elseif (strcmp(type,'mysigmoid'))
                gamma = scale;
                modelTemp = fitcsvm(trainingX,trainingY,'KernelFunction','mysigmoid',...
            'BoxConstraint',C,'Standardize',Standardize);
            end
            predictLabel = predict(modelTemp,testX);
            err10 = sum(testY.*~predictLabel)./sum(testY);
            err01 = sum(~testY.*predictLabel)./sum(~testY);
            sumError = sumError + (err10 + err01)/2;
        end                
        fres(index1,index2)= sumError ./ kfold; % canonical cross validation error
        index2 = index2+1;
    end
    index1 = index1+1;    
end

minV = min(min(fres));
[row, col] = find(fres == minV);
C = 2.^(dx*(row-1)+xmin);
gammaopt = 2.^(dy*(col-1)+ymin);
fprintf('min CV %2.3f\n',minV);
fprintf('C = %f,gamma = %f \n',C,gammaopt);

if(showGraph)
    contour(xmin:dx:xmax, ymin:dy:ymax,fres','showtext','on');
end

end